package com.example.pei.ithinklearnt.view.fragments;



import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.pei.ithinklearnt.AppApplication;
import com.example.pei.ithinklearnt.R;
import com.example.pei.ithinklearnt.adapter.mViewPageAdapter;
import com.example.pei.ithinklearnt.bean.UserInfo;
import com.example.pei.ithinklearnt.present.PersonalPresent;
import com.example.pei.ithinklearnt.present.PersonalPresentImp;
import com.example.pei.ithinklearnt.view.activity.FrescoLoaderPicturesActivity;
import com.example.pei.ithinklearnt.view.activity.MainActivity;
import com.example.pei.ithinklearnt.view.customview.headChooseDialog;
import com.example.pei.ithinklearnt.view.fragments.innerfragments.DetailedInformationFragment;
import com.example.pei.ithinklearnt.view.fragments.innerfragments.PersonalDynamicsFragment;
import com.example.pei.ithinklearnt.view.interfaces.PersonalInterface;
import com.makeramen.roundedimageview.RoundedImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.iwf.photopicker.utils.PermissionsConstant;
import me.iwf.photopicker.utils.PermissionsUtils;

import static android.app.Activity.RESULT_OK;
import static com.example.pei.ithinklearnt.utils.ImageLoaderUtil.displayImage;
import static com.example.pei.ithinklearnt.utils.ImageLoaderUtil.getPhotoImageOption;
import static com.example.pei.ithinklearnt.utils.ImageLoaderUtil.getPhotoImageOption2;
import static com.example.pei.ithinklearnt.utils.MyUtils.getAge;
import static com.example.pei.ithinklearnt.utils.PermisionUtil.achieveAllPermisions;
import static com.example.pei.ithinklearnt.utils.PermisionUtil.checkWritePermission;
import static com.example.pei.ithinklearnt.utils.SnackbarUtil.ShowSnackbar;

// TODO: 2018/3/13 第一次进入程序，点击更换头像时还没有通过权限申请，图片选择方式就已经出来了 
// TODO: 2018/3/13 个人界面如果头像没有正常显示出来就非常丑！！！！

public class PersonalFragment extends Fragment implements PersonalInterface {

    private List<Fragment> fragments = new ArrayList<Fragment>();
    ;

    private PersonalPresent personalPresent;


    private headChooseDialog dialog;

    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int CROP_REQUEST_CODE = 3;

    private int choosefor;
    private int coverWidth;
    private int coverHeight;

    private UserInfo displayUser;   //当前fragment应当显示的用户
    private boolean isCurrent;     //判断展示的用户是不是当前用户  是 true

    @BindView(R.id.tl_table)
    TabLayout tabLayout_table;
    @BindView(R.id.fragment_contain)
    ViewPager viewPager;
    @BindView(R.id.iv_cover)
    ImageView imageView_cover;
    @BindView(R.id.rv_head)
    RoundedImageView imageView_head;
    @BindView(R.id.ib_choosecover)
    ImageButton imageButton_choosecover;
    @BindView(R.id.tv_username)
    TextView textView_username;
    @BindView(R.id.tv_userage)
    TextView textView_userage;

    @BindView(R.id.iv_sex)
    ImageView imageView_sex;

    private int currentPage=0;

    public static  PersonalFragment newInstance(UserInfo userInfo,int pos) {
        PersonalFragment fragment = new PersonalFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("u", userInfo);
        bundle.putInt("pos",pos);
        fragment.setArguments(bundle);  //设置参数

        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            displayUser = (UserInfo) getArguments().getSerializable("u");
            currentPage=getArguments().getInt("pos");
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.personalmenu_fragment, container, false);
        ButterKnife.bind(this, rootView);

        if (displayUser == null) {
            displayUser = AppApplication.getCurrentUser();
        }
        personalPresent = new PersonalPresentImp(this, displayUser);
        isCurrent = displayUser.getObjectId().equals(AppApplication.getCurrentUser().getObjectId());
        initViews();

        return rootView;
    }


    private void initViews() {


        fragments.add(PersonalDynamicsFragment.newInstance(displayUser));
        fragments.add(DetailedInformationFragment.newInstance(displayUser));
        String[] titles = new String[]{"个人动态", "技能卡"};
        mViewPageAdapter personalViewPageAdapter = new mViewPageAdapter(getChildFragmentManager(), fragments, titles);
        viewPager.setAdapter(personalViewPageAdapter);

        tabLayout_table.setupWithViewPager(viewPager);
        viewPager.setCurrentItem(currentPage);

        //获取本地封面\
        personalPresent.getCoverImage();
        //获取本地头像
        personalPresent.getHeadImage();

        textView_username.setText(displayUser.getNickName());
        textView_userage.setText(getResources().getString(R.string.age, getAge(displayUser.getBirthDay())));
        if (displayUser.getSex() == 0) {
            imageView_sex.setBackgroundResource(R.drawable.female);
        } else {
            imageView_sex.setBackgroundResource(R.drawable.male);
        }


        imageButton_choosecover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //选择新封面
                chooseImage(2, imageView_cover.getMeasuredWidth(), imageView_cover.getMeasuredHeight());
            }
        });
        imageView_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isCurrent) {
                    //选择新头像
                    chooseImage(1, 0, 0);
                } else {
                    Intent intent = new Intent(getContext(), FrescoLoaderPicturesActivity.class);
                    ArrayList<String> arrayList = new ArrayList<>();
                    arrayList.add(displayUser.getHeadFileUrl());
                    intent.putStringArrayListExtra("photoUris", arrayList);
                    startActivity(intent);
                }
            }
        });

        if (!isCurrent) {//如果不是当前用户
            imageButton_choosecover.setVisibility(View.GONE);
            //   imageView_head.setClickable(false);
        }


    }


    //打开侧滑栏
    @OnClick(R.id.button_set)
    void openMenu(){
        MainActivity parentActivity = (MainActivity) getActivity();
        parentActivity.openMenu();
    }
    @Override
    public void onResume() {
        super.onResume();
        //刷新个人信息
        updateInformation();
    }

    //更新自己的信息，昵称，性别，头像可能被修改了
    private void updateInformation(){
        if(isCurrent){
            //是当前用户
            UserInfo u=AppApplication.getCurrentUser();
            //获取本地头像
            personalPresent.getHeadImage();

            textView_username.setText(u.getNickName());
            textView_userage.setText(getResources().getString(R.string.age, getAge(u.getBirthDay())));
            if (u.getSex() == 0) {
                imageView_sex.setBackgroundResource(R.drawable.female);
            } else {
                imageView_sex.setBackgroundResource(R.drawable.male);
            }
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser) {
            if (fragments.get(0) != null) {
                fragments.get(0).setUserVisibleHint(true);
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
        } else {
            switch (requestCode) {
                case IMAGE_REQUEST_CODE:
                    personalPresent.getPhotoAndCrop(choosefor, data.getData(), IMAGE_REQUEST_CODE, CROP_REQUEST_CODE, coverWidth, coverHeight);
                    break;
                case CAMERA_REQUEST_CODE:
                    personalPresent.getPhotoAndCrop(choosefor, null, CAMERA_REQUEST_CODE, CROP_REQUEST_CODE, coverWidth, coverHeight);
                    break;
                case CROP_REQUEST_CODE:
                    personalPresent.CropCallback(choosefor, data);
                    break;
            }
        }
    }


    @Override
    public void setShowSnackbar(boolean success,int w) {
        if (success) {
            ShowSnackbar(getActivity().findViewById(R.id.coordinatorlayout), "设置成功~", "#FFAF70", "#ffffff", 16);
        } else {
            ShowSnackbar(getActivity().findViewById(R.id.coordinatorlayout), " 信息更新失败", "#FFAF70", "#ffffff", 16);
        }
        if(w==1){
            //重新加载封面
            MainActivity main=(MainActivity)getActivity();
            main.initCoverImage();
        }
    }

    @Override
    public void setCoverImageBitmap(Bitmap bitmap) {
        imageView_cover.setImageBitmap(bitmap);
    }

    @Override
    public void setHeadImageBitmap(Bitmap bitmap) {
        imageView_head.setImageBitmap(bitmap);
        //this.startActivity();
    }

    @Override
    public void setHeadImageBitmap(String url) {
        displayImage(getContext(), imageView_head, url, getPhotoImageOption2());
    }

    @Override
    public void setCoverImageBitmap(String url) {
        if(url==null||url.equals("")){
            imageView_cover.setImageResource(R.drawable.banner_default);
        }else{
            displayImage(getContext(), imageView_cover, url, getPhotoImageOption());
        }
    }

    @Override
    public Activity getActivityy() {
        return getActivity();
    }

    @Override
    public Fragment get() {
        return this;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            switch (requestCode) {
                case 104:
                    if (PermissionsUtils.checkWriteStoragePermission(this) &&
                            PermissionsUtils.checkCameraPermission(this)) {
                        chooseImage(wayy,widthh,heightt);
                    }
                    break;
            }
        }
    }

    /**
     * 下面三个变量是给上面权限回调使用的。。。很糟糕的设计
     */
    private int wayy;
    private int widthh;
    private int heightt;
    //弹出dialog到相册或者相机选择图片
    public void chooseImage(int way, int width, int height) {
        wayy=way;
        widthh=width;
        heightt=height;
        //权限适配
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            if (PermissionsUtils.checkWriteStoragePermission(this) &&
                    PermissionsUtils.checkCameraPermission(this)) {
                c(wayy,widthh,heightt);
            }else{
                //请求活动
                Context context=getContext();
                if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                        ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                        ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ) {
                    requestPermissions(new String[]{
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.CAMERA}, 104);
                }
            }
        }else{
            //弹出dialog到相册或者相机选择图片
            c( way, width, height);
        }
    }
    //弹出dialog到相册或者相机选择图片
    private void c(int way, int width, int height){
        choosefor = way;
        if (way == 2) {
            //选择的是封面
            coverWidth = width;
            coverHeight = height;
        }

        View view = getLayoutInflater().inflate(R.layout.photo_choose_dialog, null);
        dialog = new headChooseDialog(getActivity(), R.style.transparentFrameWindowStyle, new headChooseDialog.LeaveMyDialogListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.btn_c:
                        break;
                    case R.id.btn_g:
                        personalPresent.choosePhotoFromAlbum(IMAGE_REQUEST_CODE);
                        break;
                    case R.id.btn_t:
                        personalPresent.choosePhotoFromCamera(CAMERA_REQUEST_CODE);
                        break;
                }
                dialog.dismiss();
            }
        });
        try {
            dialog.setContentView(view, new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT));
            Window window = dialog.getWindow();
            // 设置显示动画
            window.setWindowAnimations(R.style.main_menu_animstyle);
            WindowManager.LayoutParams wl = window.getAttributes();
            wl.x = 0;
            wl.y = getActivity().getWindowManager().getDefaultDisplay().getHeight();
            // 以下这两句是为了保证按钮可以水平满屏
            wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
            wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;

            // 设置显示位置
            dialog.onWindowAttributesChanged(wl);
            // 设置点击外围解散
            dialog.setCanceledOnTouchOutside(true);
            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}